require 'extract/rules/xml_rule'
require 'singleton'
require 'enum'


module Extract
  
  class LastfmRules < Enum
    
    public
    
    #define de Brightkite extractions rules
    
    class FullName < XMLRule
      def xpath
        "lfm[@status='ok']/user/realname[text()]"
      end
      
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.full_name = val
      end
      
      def preproces_val(val)
        super val
        val.strip!
      end
    end
    
    class FirstName < FullName
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.first_name = val.eql?("") ? nil : val
      end
      
      def preproces_val(val)
        super val
        d = val.match /(\w+) (\w+)/
        if !d.nil? then
          val.replace d[1]
        else
          val.replace ""
        end
      end
    end
    
    class LastName < FullName
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.last_name = val.eql?("") ? nil : val
      end
      
      def preproces_val(val)
        super val
        d = val.match /(\w+) (\w+)/
        if !d.nil? then
          val.replace d[2]
        else
          val.replace ""
        end
      end
    end
    
    class Gender < XMLRule
      def xpath
        "lfm[@status='ok']/user/gender[text()]"
      end
      
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.gender = val.eql?('m') ? 'male' : 'female'
      end
    end
    
    
    class Country < XMLRule
      def xpath
        "lfm[@status='ok']/user/country[text()]"
      end
      
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.locale_country = val
      end
    end
    
    class Age < XMLRule
      def xpath
        "lfm[@status='ok']/user/age[text()]"
      end
      
      protected
      
      def handle_val(val, dest_receiver)
        dest_receiver.age = val.to_i
      end
    end
    
    protected
    
    def initialize
      super()
      @collections[:Country] = Country.instance
      @collections[:FullName] = FullName.instance
      @collections[:Age] = Age.instance
      @collections[:Gender] = Gender.instance
      @collections[:FirstName] = FirstName.instance
      @collections[:LastName] = LastName.instance
    end
    
  end
  
end